package com.hyd.hx_adr.modules.patient.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyd.hx_adr.domain.entity.JsonResult;
import com.hyd.hx_adr.domain.info.BaseBatchInfo;
import com.hyd.hx_adr.domain.info.BaseInfo;
import com.hyd.hx_adr.exception.BusinessException;
import com.hyd.hx_adr.modules.patient.domain.QueryPatientInfo;
import com.hyd.hx_adr.modules.patient.domain.entity.Patient;
import com.hyd.hx_adr.modules.patient.domain.vo.ImportPatientVo;
import com.hyd.hx_adr.modules.patient.domain.vo.PatientVo;
import com.hyd.hx_adr.modules.patient.mapper.PatientMapper;
import com.hyd.hx_adr.modules.patient.service.PatientService;
import com.hyd.hx_adr.utils.ImportExcelUtils;
import com.hyd.hx_adr.utils.ResultUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> importPatient(MultipartFile file) {
        try {
            List<ImportPatientVo> listData = ImportExcelUtils.getListData(file, ImportPatientVo.class, 2);
            if (listData.isEmpty())
                return ResultUtils.error("未读取到表格数据，请检查文件是否正确");

            List<Patient> patientList = new ArrayList<>();
            listData.forEach(item -> {
                Patient patient = new Patient();
                patient.setAdmissionNumber(item.getAdmissionNumber());
                patient.setCaseNumber(item.getCaseNumber());
                patient.setEthnicity(item.getEthnicity().equals("汉族") ? 1 : 0);
                patient.setMaritalStatus(item.getMaritalStatus());
                patient.setGender(item.getGender());
                patient.setAge(Integer.parseInt(item.getAge().replaceAll("岁", "")));
                patient.setHeight(item.getHeight());
                patient.setWeight(item.getWeight());
                patient.setAllergyHistory(item.getAllergyHistory());
                patient.setSmokingHistory(item.getSmokingHistory());
                patient.setAverageCigarettesPerDay(item.getAverageCigarettesPerDay());
                patient.setSmokingYears(item.getSmokingYears());
                patient.setQuitSmoking(item.getQuitSmoking());
                patient.setQuitSmokingYears(item.getQuitSmokingYears());
                patient.setDrinkingHistory(item.getDrinkingHistory());
                patient.setAverageAlcoholPerDay(item.getAverageAlcoholPerDay());
                patient.setDrinkingYears(item.getDrinkingYears() != null ? item.getDrinkingYears().intValue() : null);
                patient.setQuitDrinking(item.getQuitDrinking());
                patient.setQuitDrinkingYears(item.getQuitDrinkingYears());
                patient.setCurrentDepartment(item.getCurrentDepartment());
                patient.setAdmissionDepartment(item.getAdmissionDepartment());
                patient.setAdmissionDiagnosis(item.getAdmissionDiagnosis());

                try {
                    patient.setAdmissionDate(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").parse(item.getAdmissionDate()));
                    patient.setDischargeDate(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").parse(item.getDischargeDate()));
                } catch (Exception e) {
                    throw new BusinessException("无法识别的日期，请按照提示的日期格式进行填充!");
                }

                patientList.add(patient);
            });

            saveBatch(patientList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public JsonResult<List<PatientVo>> getPatientList(QueryPatientInfo info) {
        if (null == info.getPage())
            info.setPage(1);
        if (null == info.getLimit())
            info.setLimit(10);

        LambdaQueryChainWrapper<Patient> queryWrapper = lambdaQuery();
        queryWrapper.isNull(Patient::getIsDeleted);
        if (StringUtils.isNotBlank(info.getAdmissionNumber()))
            queryWrapper = queryWrapper.like(Patient::getAdmissionNumber, info.getAdmissionNumber());

        if (StringUtils.isNotBlank(info.getCaseNumber()))
            queryWrapper = queryWrapper.like(Patient::getCaseNumber, info.getCaseNumber());

        Page<Patient> page = queryWrapper.page(new Page<>(info.getPage(), info.getLimit()));
        List<PatientVo> voList = new ArrayList<>();
        page.getRecords().forEach(item -> {
            PatientVo vo = new PatientVo();
            BeanUtil.copyProperties(item, vo);
            voList.add(vo);
        });
        return ResultUtils.success(voList, page.getTotal());
    }

    @Override
    public JsonResult<Patient> queryPatientById(BaseInfo info) {
        Patient patient = getById(info.getId());
        if (null == patient)
            return ResultUtils.error("患者数据不存在");

        return ResultUtils.success(patient);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> deletePatient(BaseBatchInfo info) {
        LambdaUpdateChainWrapper<Patient> wrapper = lambdaUpdate()
                .in(Patient::getId, info.getIds())
                .set(Patient::getIsDeleted, info.getOwner());
        wrapper.update();
        return ResultUtils.success();
    }
}
